import {Component, OnInit} from '@angular/core';
import {Page} from '../../../public/util/page';
import {SettingUrl} from '../../../public/setting/setting_url';
import {SettingService} from '../setting.service';
import {Util} from '../../../public/util/util';
import {Setting} from '../../../public/setting/setting';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.css']
})
export class SettingComponent implements OnInit {
  public listData: Page = new Page(); //设置
  public routerLinks = SettingUrl.ROUTERLINK;//路由
  public _loading: boolean = false;
  public editCache = {};
  public appDataKey: string = Setting.appHomeDesKey;
  public msgTip = Setting.msgTip;

  constructor(private settingService: SettingService) {
  }

  ngOnInit() {
    this.getList();
  }

  /**
   * 查询设置列表
   * @param curPage 当前页
   */
  getList(curPage?: number) {
    let me = this;
    me._loading = true;
    if (curPage) me.listData.curPage = curPage;//当有页码时，查询该页数据
    me.listData.params = {
      curPage: me.listData.curPage, //目标页码
      pageSize: 1000, //每页条数
    };
    me.settingService.list(me.listData.params).then((res: Page) => {
      me._loading = false;
      if (res) {
        me.listData = res;
        this.updateEditCache();
      }
    }).catch(res => me._loading = false);
  }

  /**
   * 创建一个对象，包含每条数据，和每条数据的编辑状态
   */
  updateEditCache() {
    this.listData.voList.forEach(item => {
      if (!this.editCache[item.id]) {
        this.editCache[item.id] = {
          edit: false,
          data: Util.deepCopy(item)
        };
      }
    });
  }

  startEdit(id) {
    this.editCache[id].edit = true;
  }

  cancelEdit(id: string): void {
    const index = this.listData.voList.findIndex(item => item.id === id);
    this.editCache[id].edit = false;
    this.editCache[id].data = Util.deepCopy(this.listData.voList[index]);
  }

  /**
   * 保存修改
   * @param id
   */
  saveEdit(id: string): void {
    let me = this;
    const index = this.listData.voList.findIndex(item => item.id === id);
    let data = {
      'k': this.editCache[id].data.k,
      'v': this.editCache[id].data.v,
      'summary': this.editCache[id].data.summary
    };
    me._loading = true;
    me.settingService.modify(data).then(res => {
      me._loading = false;
      if (res) {
        this.listData.voList[index] = Util.deepCopy(this.editCache[id].data);//成功后直接本地替换数据
        this.editCache[id].edit = false;//修改状态改为false
      }
    }).catch(res => me._loading = false);
  }

}
